package org.ndx.majick.ui.file;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.JComponent;

import org.ndx.majick.properties.Property;

/**
 * Updates view component depending upon infos coming from both a meatadata and a file property
 * @author Nicolas Delsaux
 *
 */
abstract class AbstractViewUpdater<ViewComponent extends JComponent> implements PropertyChangeListener {
	/** label to update */
	protected final ViewComponent viewComponent;
	/** view configuration */
	private FilePropertyMetadata metadata;
	/** source property */
	private Property<File> source;

	public AbstractViewUpdater(ViewComponent viewText, FilePropertyMetadata fileMeta,
			Property<File> source) {
		this.viewComponent = viewText;
		this.metadata = fileMeta;
		this.source = source;
		metadata.addPropertyChangeListener(this);
		source.addPropertyChangeListener(this);
		updateView();
	}
	
	private void updateView() {
		if(source.get()==null) {
			setViewText("");
		} else {
			if(metadata.showFullPath.get()) {
				setViewText(source.get().getAbsolutePath());
			} else {
				if(metadata.showExtension.get()) {
					setViewText(source.get().getName());
				} else {
					String name = source.get().getName();
					setViewText(name.substring(0, name.indexOf(".")));
				}
			}
		}
	}

	/** Called each time file path is changed, this method is used to change viewed text */
	protected abstract void setViewText(String path);

	@Override
	protected void finalize() throws Throwable {
		source.removePropertyChangeListener(this);
		metadata.removePropertyChangeListener(this);
	}

	public void propertyChange(PropertyChangeEvent evt) {
		updateView();
	}
}